from django.db import models
from random import randint
from django.utils import timezone


# Create your models here.
class QuestionManage(models.Model):
    start = models.DateTimeField()
    finish = models.DateTimeField()
    visit_code = models.IntegerField(default=0)
    visit_count = models.IntegerField(default=0)
    commit_count = models.IntegerField(default=0)
    def __str__(self):
        return self.start.strftime("%Y-%M-%d %H:%M:%S") + " [{}]".format(self.visit_code)


class Questions(models.Model):
    question_text = models.CharField(max_length=1024)
    question_type = models.IntegerField(default=0)
    question_must = models.BooleanField(default=False)

    def __str__(self):
        return self.question_text


class QuestionOptions(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    option_text = models.CharField(max_length=1024)

    def __str__(self):
        return self.question.question_text[:10] + "..." + ":" +self.option_text


class Results(models.Model):
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    answer = models.CharField(max_length=1024)
    visit_code = models.IntegerField(default=0)
    commit_time = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return str(self.visit_code) + ":" + self.answer


class MyQuestion():
    def __init__(self):
        self.commit_count = 0
        self.visit_count = 0
        self.visit_code = None
        self.start_time = None
        self.finish_time = None
        self.question_list = []
        self.status = 'stop'

    def getStatus(self):
        return self.status

    def getStartTime(self):
        return self.start_time

    def getVisitCode(self):
        return self.visit_code

    def _getRandomNum(self):
        num = randint(1000, 9999)
        while True:
            try:
                Results.objects.get(visit_code=num)
            except Results.DoesNotExist:
                return num
            num = randint(1000, 9999)

    def startQuestion(self):
        self.visit_code = self._getRandomNum()
        self.visit_count = 0
        self.commit_count = 0
        self.start_time = timezone.now()
        self.createQuestions()
        self.status = 'running'

    def createQuestions(self):
        all_questions = Questions.objects.all()
        self.question_list = []
        count = 1
        for q in all_questions:
            if q.question_type == 1:
                use_type = 'radio'
            elif q.question_type == 2:
                use_type = 'check'
            elif q.question_type == 3:
                use_type = 'input'
            else:
                use_type = ''

            option_list = []
            for option in q.questionoptions_set.all():
                option_list.append(option.option_text)

            item = {
                'id': q.id,
                'no': count,
                'question_text': q.question_text,
                'type': use_type,
                'must': '必选' if q.question_must else '',
                'option_list': option_list
            }
            self.question_list.append(item)
            count += 1

    def getResults(self,visit_code):
        all_questions = Questions.objects.all()
        result_list = []
        for q in all_questions:
            results = q.results_set.filter(visit_code=visit_code)
            for item in results:
                ret = {
                    'question_id': q.id,
                    'answer': item.answer,
                    'visit_code': item.visit_code,
                    'commit_time': item.commit_time
                }
                result_list.append(ret)
        return result_list

    def getDescribe(self):
        all_msg = QuestionManage.objects.all()
        result_list = []
        for msg in all_msg:
            item = {
                'start': msg.start.strftime('%Y-%m-%d %H:%M:%S'),
                'finish': msg.finish.strftime('%Y-%m-%d %H:%M:%S'),
                'visit_code': msg.visit_code,
                'visit_count': msg.visit_count,
                'commit_count': msg.commit_count
            }
            result_list.append(item)
        return result_list

    def getAllQuestions(self):
        all_questions = Questions.objects.all()
        question_list = []
        for q in all_questions:
            item = {
                'id': q.id,
                'question_text': q.question_text,
                'type': q.question_type,
                'must': q.question_must,
            }
            question_list.append(item)
        return question_list


    def getQuestions(self):
        return self.question_list

    def stopQuestion(self):
        self.finish_time = timezone.now()
        q = QuestionManage(start=self.start_time, finish=self.finish_time,
                           visit_count=self.visit_count, commit_count=self.commit_count,
                           visit_code=self.visit_code)
        q.save()
        self.status = 'stop'
